// pages/songDetail/songDetail.js
import PubSub from 'pubsub-js'
import moment from 'moment'
import request from '../../../utils/request'
//获取全局实例
const appInstance = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //标识音乐是否在播放
    isPlay: false,
    song: [],
    musicId: '',
    musicLink: '',
    currentTime: '00:00',
    durationTime: '00:00',
    currentWidth:0, //播放进度条显示的进度

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //options 接收路由传参的参数
    let musicId = options.musicId
    this.setData({
      musicId
    })

    this.getSong(musicId)

    //判断当前的音乐是否还在播放
    if (appInstance.globalData.isMusicPlay === true && appInstance.globalData.musicId == musicId) {
      this.setData({
        isPlay:true
      })
    }
    //添加音乐的相关监视功能 ---解决手机通知栏跟小程序页面播放暂停显示不一致的状态
    this.audioManager = wx.getBackgroundAudioManager()
    //监视音乐的播放
    this.audioManager.onPlay(() => {
      this.setData({
        isPlay:true
      })
      //修改全局是否播放的状态
      appInstance.globalData.isMusicPlay = true
      appInstance.globalData.musicId = this.data.musicId
    })
    //监听音乐的暂停
    this.audioManager.onPause(() => {
      this.setData({
        isPlay:false
      })
      appInstance.globalData.isMusicPlay = false
    })
    //监听音乐停止事件
    this.audioManager.onStop(() => {
       this.setData({
        isPlay:false
       })
      appInstance.globalData.isMusicPlay = false
    })
    //监听音乐播放结束
    this.audioManager.onEnded(()=>{
      //自动切换下一首音乐，并且自动播放
      PubSub.subscribe("musicId", (msg, musicId) => {
      this.getSong(musicId)
      this.musicControl(true, musicId)
      PubSub.unsubscribe("musicId")
    })
      PubSub.publish("switchType", 'next')
      //将实时进度条的长度变成0
      this.setData({
        currentWidth: 0,
        currentTime:'00:00'
      })
    })
    //监听音乐进度变化
    this.audioManager.onTimeUpdate(()=>{
      // 格式化的实时时间
      let currentTime = moment(this.audioManager.currentTime * 1000).format('mm:ss')
      let currentWidth = (this.audioManager.currentTime / this.audioManager.duration)*100
      this.setData({
        currentTime,
        currentWidth
      })
    })
  },
  // 点击播放暂停的回调
  handleMusicPlay() {
    let isPlay = !this.data.isPlay
    // this.setData({
    //   isPlay: !this.data.isPlay
    // })
    let {musicId, musicLink} = this.data;
    this.musicControl(isPlay, musicId, musicLink);
  },
  //控制音乐的暂停播放
  async musicControl(isPlay, musicId, musicLink) {
    //创建控制音乐播放的实例对象
    if (isPlay) {
      if (!musicLink) {
        // 获取音乐播放链接
        let songUrlData = await request('/song/url', {id: musicId});
        musicLink = songUrlData.data[0].url;

        this.setData({
          musicLink
        })
      } else {

      }
      //播放音乐
      this.audioManager.title = this.data.song.name
      this.audioManager.src = musicLink
    } else {
      //暂停音乐播放
      this.audioManager.pause()
    }
  },


  //获取音乐详情
  async getSong(musicId) {
    let songData = await request('/song/detail', { ids: musicId })
    let durationTime = moment(songData.songs[0].dt).format("mm:ss",)
    this.setData({
      song: songData.songs[0],
      musicId,
      durationTime
    })

    //动态修改窗口的标题
    wx.setNavigationBarTitle({
      title: this.data.song.name,
    })
  },

  //切换上一首或者下一首
  handleSwitch(event) {
    //获取切换的类别
    let type = event.currentTarget.id
    // 关闭当前播放的音乐
    this.audioManager.stop();
    //订阅来自推荐界面发布的id
    PubSub.subscribe("musicId", (msg, musicId) => {
      this.getSong(musicId)
      this.musicControl(true, musicId)
      PubSub.unsubscribe("musicId")
    })

    //发布消息给recommendSong界面
    PubSub.publish("switchType", type)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})